#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@IDE     ：PyCharm 
@Author  ：kiway
@Date    ：2024/11/10 13:01 
"""
import asyncio
import csv
import ccxt.pro
import traceback
import os

config_future = {"id": "binance",
                 "options": {'defaultType': 'future'}
                 }

exchange_furture = getattr(ccxt.pro, config_future['id'])({
    'options': config_future['options'],
})

exchange_furture.set_sandbox_mode(True)

config_spot = {"id": "binance",
               "options": {'defaultType': 'spot'}
               }

exchange_spot = getattr(ccxt.pro, config_spot['id'])({
    'options': config_spot['options'],
})

exchange_spot.set_sandbox_mode(True)


def ensure_csv_file(file_name):
    if not os.path.exists(file_name):
        with open(file_name, 'w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            # 写入表头
            writer.writerow(["e", "E", "s", "a", "p", "q", 'f', "l", "T", "m", "M"])


def write_to_csv(file_name, data):
    ensure_csv_file(file_name)

    with open(file_name, 'a', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(data)


async def on_aggTrade(symbol, aggTrade):
    data = list(aggTrade[0]["info"].values())
    write_to_csv(symbol, data)


async def get_aggTrade_future():
    while True:
        try:
            agg_trade = await exchange_furture.watch_trades_for_symbols(["BTC/USDT:USDT", "ETH/USDT:USDT"],
                                                                        params={"name": "aggTrade"})

            symbol_str = agg_trade[0]["symbol"]
            await on_aggTrade(symbol_str, agg_trade)

        except:
            traceback.print_exc()


async def get_aggTrade_spot():
    while True:
        try:
            agg_trade = await exchange_spot.watch_trades_for_symbols(["BTC/USDT", "ETH/USDT"],
                                                                     params={"name": "aggTrade"})

            symbol_str = agg_trade[0]["symbol"].replace("/", "")
            await on_aggTrade(symbol_str, agg_trade)

        except:
            traceback.print_exc()


async def get_bar_spot():
    while True:
        try:
            bars = await exchange_spot.watch_ohlcv_for_symbols([["BTC/USDT", "1m"], ["ETH/USDT", "1m"]])

            symbol_str = list(bars.keys())[0]
            await on_aggTrade(symbol_str, bars)

        except:
            traceback.print_exc()


async def get_bar_future():
    while True:
        try:
            bars = await exchange_furture.watch_ohlcv_for_symbols([["BTC/USDT:USDT", "1m"], ["ETH/USDT:USDT", "1m"]])

            symbol_str = list(bars.keys())[0]
            await on_aggTrade(symbol_str, bars)

        except:
            traceback.print_exc()


loop = asyncio.get_event_loop()

loop.create_task(get_aggTrade_spot())
# loop.create_task(get_aggTrade_future())
# loop.create_task(get_bar_future())
# loop.create_task(get_bar_spot())
loop.run_forever()
